<template>
  <div class="side-console">
    <div class="side-console-content">
      <div class="close-btn">
        <i @click="viewReferences()" class="el-icon-close"></i>
      </div>
      <div class="header-container">
        <div class="title-container">
          <div class="title">
            <div>引用列表</div>
          </div>
          <svg-icon
            style="width: 15px; height: 15px; margin-right: 10px"
            :icon-class="!isAutoExpand ? 'newDingG' : 'newDingB'"
            @click="handleChange"
          />
        </div>
      </div>
      <div class="content-container">
        <el-collapse accordion>
          <el-collapse-item
            v-for="reference in processedItems"
            :key="reference.id"
            :name="reference.id"
            class="text-title"
          >
            <template slot="title">
              <div class="show-left" :title="reference.file_name">
                {{ reference.file_name }}
              </div>
              <div class="show-middle">
                <span>相关性：</span
                ><span>{{ getFormattedScore(reference.score) }}</span>
              </div>
              <div class="show-right">
                <i
                  @click="
                    () => {
                      viewText(reference);
                    }
                  "
                  class="el-icon-document"
                ></i>
              </div>
            </template>
            <div>
              <span  v-for=" (item,index) in reference.contentList" :key="index"> <a class="text-link" @click="pdfContent( reference,item)"> {{ item }}</a></span>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <el-drawer
      :title="params.fileName"
      :visible.sync="drawer"
      direction="ltr"
      :before-close="handleClose"
      append-to-body
      :size="1000"
    >
      <div class="box-height" v-if="drawer">
        <FileViewDrawer
          :fileType="fileType"
          :fileSrc="fileSrc"
          :docBlocksList="docBlocksList"
          :docBlocksType="docBlocksType"
          :chunkText="chunkText"
        ></FileViewDrawer>
      </div>
    </el-drawer>
  </div>
</template>
  
  <script>
import { getFileUrlQa, getDocumentChunk } from "@/api/knowledge/file";
import FileViewDrawer from "./FileViewDrawer.vue";
export default {
  name: "ReferenceList",
  components: { FileViewDrawer },
  props: {
    referenceList: {
      type: Array,
      default: [],
    },
  },
  computed: {
    processedItems() {
      // 在这里对 files 数组进行处理
      return this.referenceList.map(item => ({
        ...item,
        contentList:item.content.split(/\s+/)
      }));
    }
  },
  data() {
    return {
      isAutoExpand: true,
      drawer: false,
      params: {
        fileId: "",
        fileName: "",
      },
      fileType: "",
      fileSrc: "",
      docBlocksList:[],
      docBlocksType:'',
      chunkText: ''
    };
  },

  created() {
    const storedValue = sessionStorage.getItem("isAutoExpand");
    if (storedValue !== null) {
      this.isAutoExpand = JSON.parse(storedValue);
    }
  },
  methods: {
    getFormattedScore(score) {
      return (score * 100).toFixed(2) + "%";
    },
    // 自动展开
    handleChange(val) {
      this.isAutoExpand = !this.isAutoExpand;
      sessionStorage.setItem("isAutoExpand", this.isAutoExpand);
      // console.log(val);
    },
    // 查看原文
    viewText(reference) {
      this.chunkText = ''
      event.stopPropagation();
      this.documentChunk(reference)
      this.fileType = reference.file_name.split(".").pop();
      this.params = {
        fileId: reference.file_id,
        fileName: reference.file_name,
      };
      this.fetchFileDetails({ fileId: reference.file_id });
    },
    pdfContent(data,text) {
      this.chunkText = ''
      this.chunkText = text
      event.stopPropagation();
      this.fileType = data.file_name.split(".").pop();
      this.params = {
        fileId: data.file_id,
        fileName: data.file_name,
      };
      this.fetchFileDetails({ fileId: data.file_id });
      this.docBlocksType = 'chunkRAG'
      this.docBlocksList = [{
        content: text,
        chunkId: '1'
      }]
    },
    documentChunk(data) {
      this.chunkText = ''
      const form = {
        kbId: data?.ragParentCategoryId,
        fileId: data?.file_id,
        content: "",
      };
      getDocumentChunk(form)
        .then((response) => {
          if (response.data?.records) {
            // 点金数据
            this.docBlocksList = response.data.records;
            this.docBlocksType = 'DJ'
          }else{
            // RAG+数据
            this.docBlocksList = response.data.chunk;
            this.docBlocksType = 'RAG'
          }
        })
        .catch((error) => {
          this.$modal.msgError("失败");
        });
    },
    fetchFileDetails(params) {
      // 获取文件类型和 URL
      getFileUrlQa(params).then((response) => {
        // this.fileSrc = process.env.VUE_APP_BASE_API + response;
        // this.drawer = true;
        if(response?.code === 200){
          this.fileSrc = process.env.VUE_APP_BASE_API + response?.data;
          this.drawer = true;
        }else{
          this.$modal.msgError(response?.msg)
        }
      });
    },
    viewReferences() {
      this.$emit("view-references");
    },
    handleClose() {
      this.drawer = false;
    },
  },
};
</script>
  
  <style scoped lang="scss">
.side-console {
  height: 100%;
  .side-console-content {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    .close-btn {
      position: absolute;
      z-index: 20;
      top: 10px;
      right: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 4px;
      border-radius: 8px;
      cursor: pointer;
    }
    .header-container {
      padding: 5px 16px 10px;
      display: flex;
      // justify-content: space-between;
      align-items: center;
      width: 100%;
      .title-container {
        display: flex;
        gap: 8px;
        justify-content: space-between;
        width: 100%;
        .title {
          font-weight: 400;
          font-size: 16px;
          color: #959595;
          line-height: 20px;
        }
        i {
          color: #409eff;
          margin-right: 10px;
          cursor: pointer;
          &.unautoExpand {
            color: #dfdfdf;
          }
        }
        .switch {
          user-select: none;
          display: inline-flex;
          align-items: center;
          font-size: 12px;
          margin-right: 20px;
          cursor: pointer;
          color: #777;
          .el-switch {
            margin-left: 6px;
          }
        }
      }
    }
    .content-container {
      height: calc(100% - 60px);
      box-sizing: border-box;
      padding: 0 16px 12px;
      display: flex;
      flex-direction: column;
      overflow: auto;
    }
  }
}
</style>
<style lang="scss">
.content-container {
  .show-right {
    // .el-link--inner {
    //   font-size: 12px;
    // }
    color: #409eff;
  }
  .show-middle {
    border-radius: 17px 17px 17px 17px;
    height: 28px;
    padding: 0 10px;
    line-height: 28px;
    border-radius: 17px 17px 17px 17px;
    border: 1px solid rgba(64, 158, 255, 0.5);
    font-size: 14px;
    color: #409eff;
  }
  .text-title {
    .el-collapse-item__header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      .show-left {
        width: 140px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .el-collapse-item__arrow {
        margin: 0;
        margin-right: 10px;
      }
    }
  }
}
.box-height {
  height: 100vh;
  display: flex;
}
.text-link:hover{
  color: #409eff;
}
</style>